package com.example.bloodbankapplication.fragment;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.example.bloodbankapplication.R;
import com.example.bloodbankapplication.entity.PersonInformationModel;
import com.example.bloodbankapplication.service.BloodBankService;

public class DonorSearchFragment  extends BaseFragment {
	private MyReceiver mReceiver;
	private EditText sBloodGroup;
	private ListView lv;
	private final String ACTION ="DonorSearchFragment";
	private String instanceUrl,accessToken ;
	private ArrayList<PersonInformationModel> list ;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.donorsearch_fragment, null);
	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		mReceiver = new MyReceiver();
		sBloodGroup = (EditText) getView().findViewById(R.id.bloodgroup);
		lv = (ListView) getView().findViewById(R.id.listview);
		
		sBloodGroup.setOnEditorActionListener(new DoneOnEditorActionListener());
		
	}
	
	class DoneOnEditorActionListener implements OnEditorActionListener {
	    @Override
	    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
	        if (actionId == EditorInfo.IME_ACTION_DONE) {

	        	hideSoftKeyPad();
	    		
	    		String bloodGroupName = sBloodGroup.getText().toString();
	    		
	    		Log.i("NCS","bloodGroupName is :"+bloodGroupName);
	    		/*String group[] = bloodGroupName.split(" ");
	    		Log.i("NCS","Group[1]  :"+group[0]+group[1]);*/
	    		
	    		instanceUrl = mPreferance.getString("Instance", "");
	    		accessToken = mPreferance.getString("Access", "");
	    		
	    		if(!getConnectivity())
	    		{
	    			showPopUp(getActivity(), getResources().getString(R.string.nonetwork));
	    		}else{
	    		String searchDonorUrl = instanceUrl+"/services/data/v29.0/query/?q=select+Name,Age__c,BloodGroup__c,City__c,Email__c,Gender__c,LastName__c,MiddleName__c,Phone__c,State__c,ZipCode__c+" +
	    				"from+DonarRegistration__c+where+Name='"+bloodGroupName+"'";
	    		
	    		Log.i("NCS","URL is :"+searchDonorUrl);
	    		
	    		Intent intent = new Intent(getActivity(),BloodBankService.class);
	    		intent.putExtra("Action", ACTION);
	    		intent.putExtra("URL", searchDonorUrl);
	    		intent.putExtra("AccessToken", accessToken);
	    		intent.putExtra("Screen", "DonorSearchFragment");
	    		intent.putExtra("Type", "");
	    		startProgressDialog();
	    		getActivity().startService(intent);
	    		}
	    	
	            return true;    
	        }
	        return false;
	    }
	}
	
	@Override
	public void onResume() {
		getActivity().registerReceiver(mReceiver, new IntentFilter(ACTION));
		super.onResume();
	}
	@Override
	public void onDestroy() {
		getActivity().unregisterReceiver(mReceiver);
		super.onDestroy();
	}
	
	class MyReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			

			
			Log.i("NCS","List of Donors response"+intent.getStringExtra("Key"));
			
			list = new ArrayList<PersonInformationModel>();
			
			try{
			JSONObject jObject = new JSONObject(intent.getStringExtra("Key"));
			JSONArray donors = jObject.getJSONArray("records");
			int count = donors.length();
			
			for(int i=0;i<count;i++){
				JSONObject persons = donors.getJSONObject(i);
				
				PersonInformationModel model = new PersonInformationModel();
				model.setName(persons.getString("Name"));
				model.setPhno(persons.getString("Phone__c"));
				model.setBloodGroup(persons.getString("BloodGroup__c"));
				model.setEmail(persons.getString("Email__c"));
				
				list.add(model);
				
			}
			
			
			stopProgressDialog();
			lv.setAdapter(new DataDisplayAdapter(list));
			
			
			
			
			}
			catch(Exception ex){
				
			}
			
			
			
		
			
		}
		
	}
	
class DataDisplayAdapter extends BaseAdapter{
		
		//scope of global variable should be entire class
		private ArrayList<PersonInformationModel> donorsList;

		public DataDisplayAdapter(ArrayList<PersonInformationModel> list) {
			// scope of local variable should be with in the block;
			donorsList = list;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return donorsList.size();
		}

		@Override
		public Object getItem(int arg3) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}
		
		class ViewHolder {
			
			public TextView name,phno;
		}

		@Override
		public View getView(int position, View v, ViewGroup arg2) {
			// TODO Auto-generated method stub
			ViewHolder holder;
			if(v == null){
				holder = new ViewHolder();
				LayoutInflater inflater = getActivity().getLayoutInflater();
				v = inflater.inflate(R.layout.datadisplay, null);
				holder.name = (TextView) v.findViewById(R.id.name);
				holder.phno = (TextView) v.findViewById(R.id.number);
				v.setTag(holder);
				
			}else{
				 holder = (ViewHolder) v.getTag();
			}
			
			
			PersonInformationModel model = donorsList.get(position);
			holder.name.setText(model.getName());
			holder.name.setTextColor(Color.RED);
			holder.phno.setText(model.getPhno());
			holder.phno.setTextColor(Color.GREEN);
			
			return v;
		}
		
	}
	


}
